package org.chen.system.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.chen.common.task.ScheduledTask;
import org.chen.common.task.TaskExecutionResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;
import java.time.format.DateTimeFormatter;

/**
 * 邮件通知服务
 */
@Service
@Slf4j
public class EmailNotificationService {

    @Autowired
    private DynamicEmailConfigService dynamicEmailConfigService;

    /**
     * 发送任务执行通知邮件
     */
    public void sendTaskExecutionNotification(ScheduledTask task, TaskExecutionResult result) {
        try {
            // 获取有效的邮件配置
            DynamicEmailConfigService.EffectiveEmailConfig emailConfig = dynamicEmailConfigService.getEffectiveEmailConfig();

            if (!emailConfig.getEnabled()) {
                log.warn("邮件功能未启用或配置不完整，跳过邮件发送");
                return;
            }

            // 创建动态邮件发送器
            JavaMailSender mailSender = dynamicEmailConfigService.createDynamicMailSender();

            // 创建邮件
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom("1905333495@qq.com", "航班任务通知系统");

            // 设置邮件基本信息
            helper.setTo(task.getEmailRecipients().toArray(new String[0]));
            helper.setSubject(String.format("航班搜索任务执行通知 - %s", task.getName()));

            // 构建邮件内容
            String htmlContent = buildEmailContent(task, result);
            helper.setText(htmlContent, true);

            // 添加Excel附件
            for (String filePath : result.getExportedFiles()) {
                if (filePath != null && new File(filePath).exists()) {
                    FileSystemResource file = new FileSystemResource(filePath);
                    helper.addAttachment(new File(filePath).getName(), file);
                }
            }

            mailSender.send(message);
            log.info("任务执行通知邮件发送成功，任务：{}, 配置来源：{}",
                    task.getName(), emailConfig.getSource());

        } catch (Exception e) {
            log.error("发送邮件失败", e);
            throw new RuntimeException("发送邮件失败: " + e.getMessage());
        }
    }

    /**
     * 发送测试邮件
     */
    public boolean sendTestEmail(String testEmail) {
        try {
            DynamicEmailConfigService.EffectiveEmailConfig emailConfig = dynamicEmailConfigService.getEffectiveEmailConfig();

            if (!emailConfig.getEnabled()) {
                log.warn("邮件功能未启用或配置不完整");
                return false;
            }

            JavaMailSender mailSender = dynamicEmailConfigService.createDynamicMailSender();

            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            // 设置发件人
            String fromEmail = "database".equals(emailConfig.getSource()) ?
                    emailConfig.getFromEmail() : emailConfig.getUsername();
            helper.setFrom(fromEmail, "航班系统测试");

            helper.setTo(testEmail);
            helper.setSubject("航班系统邮件配置测试");

            String testContent = buildTestEmailContent(emailConfig);
            helper.setText(testContent, true);

            mailSender.send(message);
            log.info("测试邮件发送成功，收件人：{}, 配置来源：{}", testEmail, emailConfig.getSource());
            return true;

        } catch (Exception e) {
            log.error("发送测试邮件失败，收件人：{}", testEmail, e);
            return false;
        }
    }

    /**
     * 构建测试邮件内容
     */
    private String buildTestEmailContent(DynamicEmailConfigService.EffectiveEmailConfig emailConfig) {

        return "<html><body>" +
                "<h2>航班系统邮件配置测试</h2>" +
                "<p>这是一封测试邮件，用于验证邮件配置是否正确。</p>" +
                "<h3>当前邮件配置信息</h3>" +
                "<table border='1' style='border-collapse: collapse; width: 100%;'>" +
                "<tr><td>配置来源</td><td>" + getConfigSourceDesc(emailConfig.getSource()) + "</td></tr>" +
                "<tr><td>SMTP服务器</td><td>" + emailConfig.getSmtpHost() + "</td></tr>" +
                "<tr><td>端口</td><td>" + emailConfig.getSmtpPort() + "</td></tr>" +
                "<tr><td>发件人</td><td>" + emailConfig.getFromEmail() + "</td></tr>" +
                "<tr><td>SSL启用</td><td>" + (emailConfig.getSsl() ? "是" : "否") + "</td></tr>" +
                "</table>" +
                "<p style='color: green;'><strong>如果您收到这封邮件，说明邮件配置正确！</strong></p>" +
                "</body></html>";
    }

    /**
     * 获取配置来源描述
     */
    private String getConfigSourceDesc(String source) {
        return switch (source) {
            case "database" -> "数据库配置（系统设置页面）";
            case "application.yml" -> "默认配置（application.yml）";
            default -> "未知";
        };
    }

    /**
     * 构建邮件内容
     */
    private String buildEmailContent(ScheduledTask task, TaskExecutionResult result) {
        StringBuilder content = new StringBuilder();
        
        content.append("<html><body>");
        content.append("<h2>航班搜索任务执行报告</h2>");
        
        // 任务基本信息
        content.append("<h3>任务信息</h3>");
        content.append("<table border='1' style='border-collapse: collapse; width: 100%;'>");
        content.append("<tr><td>任务名称</td><td>").append(task.getName()).append("</td></tr>");
        content.append("<tr><td>航线</td><td>").append(task.getDeparture()).append(" → ").append(task.getDestination()).append("</td></tr>");
        content.append("<tr><td>执行时间</td><td>").append(result.getExecuteTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("</td></tr>");
        content.append("<tr><td>执行状态</td><td>").append(result.isSuccess() ? "成功" : "失败").append("</td></tr>");
        content.append("<tr><td>总耗时</td><td>").append(result.getTotalDuration()).append("毫秒</td></tr>");
        content.append("</table>");
        
        // 搜索结果详情
        content.append("<h3>搜索结果</h3>");
        content.append("<table border='1' style='border-collapse: collapse; width: 100%;'>");
        content.append("<tr><th>搜索期间</th><th>出发日期</th><th>返程日期</th><th>航班数量</th><th>最低价格</th><th>耗时</th></tr>");
        
        for (TaskExecutionResult.SearchResult searchResult : result.getSearchResults()) {
            content.append("<tr>");
            content.append("<td>").append(searchResult.getSearchPeriod()).append("</td>");
            content.append("<td>").append(searchResult.getDepartDate()).append("</td>");
            content.append("<td>").append(searchResult.getReturnDate() != null ? searchResult.getReturnDate() : "-").append("</td>");
            content.append("<td>").append(searchResult.getFlightCount()).append("</td>");
            content.append("<td>").append(searchResult.getLowestPrice()).append("</td>");
            content.append("<td>").append(searchResult.getSearchDuration()).append("ms</td>");
            content.append("</tr>");
        }
        content.append("</table>");
        
        // 导出文件信息
        if (!result.getExportedFiles().isEmpty()) {
            content.append("<h3>导出文件</h3>");
            content.append("<ul>");
            for (String filePath : result.getExportedFiles()) {
                if (filePath != null) {
                    String fileName = new File(filePath).getName();
                    content.append("<li>").append(fileName).append("</li>");
                }
            }
            content.append("</ul>");
        }
        
        content.append("</body></html>");
        
        return content.toString();
    }
}